package cc.fs.myproject;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMapOptions;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.overlay.PoiOverlay;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiItemDetail;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class GaoDeMapActivity extends BaseActivity implements LocationSource, AMapLocationListener {

    @InjectView(R.id.map)
    MapView mapView;
    @InjectView(R.id.id_toolbar)
    Toolbar idToolbar;
    @InjectView(R.id.checkBtn)
    Button checkBtn;
    @InjectView(R.id.src)
    EditText src;
    @InjectView(R.id.target)
    AutoCompleteTextView target;

    private AMap aMap;
    private Marker mGPSMarker;
    private LocationManagerProxy mAMapLocationManager;
    private String address;
    private String cityId;
    private int currentPage;
    private PoiSearch.Query query;
    private LatLonPoint mLatLng;

    public static void start(Context context) {
        Intent intent = new Intent(context, GaoDeMapActivity.class);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gao_de_map);
        ButterKnife.inject(this);
        mapView.onCreate(savedInstanceState);// 必须要写

        idToolbar.setTitle("高德地图");
        idToolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
        setSupportActionBar(idToolbar);
        init();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_gao_de_map, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_action1) {
            aMap.setMapType(AMap.MAP_TYPE_NORMAL);
            return true;
        }

        if (id == R.id.action_action1) {
            aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 初始化AMap对象
     */
    private void init() {
        setUpMap();
        mAMapLocationManager = LocationManagerProxy.getInstance(this);
        mAMapLocationManager.setGpsEnable(false);
        mAMapLocationManager.requestLocationData(LocationProviderProxy.AMapNetwork, -1, 10, this);

        checkBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchSome();
            }
        });

        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mGPSMarker.setPosition(latLng);
                aMap.invalidate();
                GeocodeSearch geocodeSearch = new GeocodeSearch(_this);
                LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude,latLng.longitude);
                RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 10, GeocodeSearch.AMAP);
                geocodeSearch.getFromLocationAsyn(query);
                geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
                    @Override
                    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                        mGPSMarker.setTitle("当前位置：");
                        mGPSMarker.setSnippet(regeocodeResult.getRegeocodeAddress().getFormatAddress());
                        mGPSMarker.showInfoWindow();
                      Log.e("------",regeocodeResult.getRegeocodeAddress().getFormatAddress());
                    }

                    @Override
                    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

                    }
                });
            }
        });

        //  输入提示的监听接口
        target.addTextChangedListener(new TextWatcher() {
            // 输入信息改变之后
            public void afterTextChanged(Editable editable) {

            }

            // 输入信息改变之前
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            // 正在输入
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                String newText = s.toString();
                // 输入信息的回调方法
                Inputtips inputTips = new Inputtips(_this, new Inputtips.InputtipsListener() {
                    @Override
                    public void onGetInputtips(List<Tip> tipList, int rCode) {
                        List<String> listString = new ArrayList<String>();
                        for (int i = 0; i < tipList.size(); i++) {
                            listString.add(tipList.get(i).getName());
                        }
                        //步骤1：设置适配器
                        target.setAdapter(new ArrayAdapter<String>(_this, android.R.layout.simple_dropdown_item_1line, listString));
                    }
                });
                try {
                    // 发送输入提示请求
                    // 第一个参数表示提示关键字，第二个参数默认代表全国，也可以为城市区号
                    inputTips.requestInputtips(newText, cityId);
                } catch (AMapException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    void searchSome() {
        currentPage = 0;
        // 第一个参数表示搜索字符串，第二个参数表示POI搜索类型，二选其一
        // 第三个参数表示POI搜索区域的编码，必设
        query = new PoiSearch.Query(target.getText().toString(), "", cityId);
        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);//设置查第一页
        PoiSearch poiSearch = new PoiSearch(this, query);
        poiSearch.setBound(new PoiSearch.SearchBound(mLatLng, 20000,true));
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult result, int rCode) {
                if(rCode == 0){
                    // 搜索POI的结果
                    if (result != null&&result.getQuery()!=null) {
                        // 是否是同一条
                        if(result.getQuery().equals(query)){
                            PoiResult poiResult = result;
                            // 取得搜索到的poiitems有多少页
                            int resultPages = poiResult.getPageCount();
                            // 取得第一页的poiitem数据，页数从数字0开始
                            List  poiItems = poiResult.getPois();
                            // 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                            List suggestionCities = poiResult.getSearchSuggestionCitys();

                            if (poiItems != null && poiItems.size() > 0) {
                                aMap.clear();//清理之前的图标
                                PoiOverlay poiOverlay = new PoiOverlay(aMap, poiItems);
                                poiOverlay.removeFromMap();
                                poiOverlay.addToMap();
                                poiOverlay.zoomToSpan();
                            } else if (suggestionCities != null
                                    && suggestionCities.size() > 0) {
//                                showSuggestCity(suggestionCities);
                            }
                        }
                    }
                }
            }

            @Override
            public void onPoiItemDetailSearched(PoiItemDetail poiItemDetail, int i) {

            }
        });
        poiSearch.searchPOIAsyn();
    }

    /**
     * 设置一些amap的属性
     */

    private void setUpMap() {
        aMap = mapView.getMap();
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.getUiSettings().setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);
    }


    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        mapView.onDestroy();
        if (mAMapLocationManager != null) {
            mAMapLocationManager.removeUpdates(this);
            mAMapLocationManager.destroy();
        }
        mAMapLocationManager = null;
        super.onDestroy();
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
    }

    @Override
    public void deactivate() {

    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            mLatLng = new LatLonPoint(aMapLocation.getLatitude(),aMapLocation.getLongitude());
            addMarker(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()));
            mapView.setVisibility(View.VISIBLE);
            cityId = aMapLocation.getCityCode();
            address = aMapLocation.getProvince() + aMapLocation.getCity() + aMapLocation.getDistrict() + aMapLocation.getStreet();
            src.setText(address);
        }
    }

    public void addMarker(LatLng latLng) {
        //定位
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        markerOption.title("我在这里:").snippet("(" + latLng.latitude + ", " + latLng.longitude + ")");
        markerOption.draggable(true);
        markerOption.icon(BitmapDescriptorFactory.defaultMarker());
        mGPSMarker = aMap.addMarker(markerOption);
        //地图移动到该位置
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14));
    }


}
